package com.gqemf.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.*;

/**
 * @program: fullstackdayone
 * @Description:
 * @author: Mr.Cheng
 * @date: 2021/10/13 11:11 上午
 */
@Service
public class FileServiceImpl implements FileService {

    private final static Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);
    /**
     * @param file
     * @Description: read file by line
     * @Param: [file]
     * @return: java.lang.String[]
     * @Author: Mr.Cheng
     * @Date: 2021/10/13 11:03 上午
     */
    @Override
    public String[] fileReading(File file) {
        if(file.exists()){
            try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
                String temp = null;
                StringBuilder content = new StringBuilder();
                //读取内容为null则表示读到了文件末尾
                while ((temp = reader.readLine()) != null) {
                    content.append(temp+";");
                }
                return content.toString().split(";");
            }catch (IOException e){
                logger.error("Can not read file",e);
            }finally {

            }
        }
        return null;
    }

    /**
     * @param contents
     * @Description: write content to txt file
     * @Param: [content]
     * @return: java.lang.Integer
     * @Author: Mr.Cheng
     * @Date: 2021/10/13 11:11 上午
     */
    @Override
    public Integer fileWriting(File file, String[] contents) {
        if(file.exists() && contents != null){
            try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)))){
                int index = 0;
                for(String content : contents){
                    writer.write(content);
                    writer.newLine();
                    index++;
                }
                return Integer.valueOf(index);
            }catch (IOException e){
                logger.error("Can not write",e);
            }finally {

            }
        }
        return null;
    }
}
